package cn.rkylin.oms.order.controller;

import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.order.service.INoteService;
import cn.rkylin.oms.order.vo.NoteVO;

/**
 * OrderNotes
 * 
 * @author wangxiaoyi
 * @version 1.0
 * @created 14-9月-2017 16:04:53
 */
@Controller
@RequestMapping("/note")
public class NoteController extends ApolloController {
    private static final Log logger = LogFactory.getLog(NoteController.class);
    /**
     * 便签服务层
     */
    @Autowired
    private INoteService noteService;

    public NoteController() {

    }

    public void finalize() throws Throwable {

    }

    /**
     * 创建便签，个人创建的便签只属于自己，其它人不能修改、删除
     * 
     * @param OrderNotes
     */
    @ResponseBody
    @RequestMapping(value = "/createNote")
    @SystemControllerLog(module = "便签", operation = "创建便签")
    public Map<String, Object> createNote(@RequestBody NoteVO noteVO) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            resultMap.put(JSON_RESULT, FAILED);
            resultMap.put(JSON_MSG, "当前用户失效");
            return resultMap;
        }
        Map<String, String> enterpriseMap = currentUser.getEnterpriseMap();
        if (enterpriseMap == null || enterpriseMap.size() == 0) {
            resultMap.put(JSON_RESULT, FAILED);
            resultMap.put(JSON_MSG, "当前用户没有企业ID");
            return resultMap;
        }
        String entId = "";
        for (Map.Entry<String, String> entry : enterpriseMap.entrySet()) {
            entId = entry.getKey();
        }
        noteVO.setEntId(entId);
        noteVO.setUpdateTime(new Date());
        noteVO.setCreateTime(new Date());
        noteVO.setOperTime(new Date());
        noteVO.setOperUserId(currentUser.getId());
        noteVO.setOperUserName(currentUser.getFullName());
        noteVO.setEntId(entId);

        Map<String, Object> map = noteService.createNote(noteVO);
        resultMap.put(JSON_RESULT, map.get("isOk"));
        resultMap.put(JSON_MSG, map.get("errorMessage"));
        return resultMap;
    }

    /**
     * createNewNote:创建便签 <br/>
     *
     * @author zhanghao
     * @param content
     *            便签内容
     * @param busiKey
     *            便签对应业务主键
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createNewNote")
    @SystemControllerLog(module = "便签", operation = "创建便签")
    public Map<String, Object> createNewNote(@RequestParam String content, @RequestParam String busiKey) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String noteContent = URLDecoder.decode(content, "UTF-8");

            logger.info(String.format("系统调用新增内部便签：/note/createNewNote/%s/%s", busiKey, noteContent));
            // 用于返回值的json对象
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser == null) {
                resultMap.put(JSON_RESULT, FAILED);
                resultMap.put(JSON_MSG, "当前用户无效");
                return resultMap;
            }
            Map<String, String> enterpriseMap = currentUser.getEnterpriseMap();
            if (enterpriseMap == null || enterpriseMap.size() == 0) {
                resultMap.put(JSON_RESULT, FAILED);
                resultMap.put(JSON_MSG, "当前用户企业信息获取失败");
                return resultMap;
            }
            String entId = "";
            for (Map.Entry<String, String> entry : enterpriseMap.entrySet()) {
                entId = entry.getKey();
            }

            Date now = new Date();

            NoteVO noteVO = new NoteVO();
            noteVO.setEntId(entId);
            noteVO.setUpdateTime(now);
            noteVO.setCreateTime(now);
            noteVO.setOperTime(now);
            noteVO.setOperUserId(currentUser.getId());
            noteVO.setOperUserName(currentUser.getFullName());
            noteVO.setNoteId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
            noteVO.setSourCodeId(busiKey);

            noteVO.setNote(noteContent);

            noteService.createNote(noteVO);
            resultMap = getSuccessMap("内部便签保存成功");
            logger.info("内部便签保存成功");
        } catch (Exception e) {
            resultMap = getFailedMap("内部便签保存异常");
            logger.error(e.getMessage());
        }
        return resultMap;
    }

    @ResponseBody
    @RequestMapping(value = "/updateExistingNote")
    @SystemControllerLog(module = "便签", operation = "修改便签", keyCode = "noteId")
    public Map<String, Object> updateExistingNote(@RequestParam String content, @RequestParam String noteId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String noteContent = URLDecoder.decode(content, "UTF-8");
            logger.info(String.format("系统调用新增内部便签：/note/updateExistingNote/%s/%s", noteId, noteContent));
            // 用于返回值的json对象

            Date now = new Date();

            NoteVO noteVO = new NoteVO();
            noteVO.setUpdateTime(now);
            noteVO.setCreateTime(now);
            noteVO.setOperTime(now);
            noteVO.setNoteId(noteId);
            noteVO.setNote(noteContent);

            noteService.updateNote(noteVO);
            resultMap = getSuccessMap("内部便签更新成功");
            logger.info("内部便签更新成功");
        } catch (Exception e) {
            resultMap = getFailedMap("内部便签更新异常");
            logger.error(e.getMessage());
        }
        resultMap.put("noteId", noteId);
        return resultMap;
    }

    /**
     * 修改便签，只能修改自己的OrderNotes，不能修改其它人的
     * 
     * @param OrderNotes
     */
    @ResponseBody
    @RequestMapping(value = "/updateNote")
    @SystemControllerLog(module = "便签", operation = "修改便签", keyCode = "noteId")
    public Map<String, Object> updateNote(@RequestBody NoteVO noteVO) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            resultMap.put(JSON_RESULT, FAILED);
            resultMap.put(JSON_MSG, "当前用户失效");
            return resultMap;
        }
        Map<String, String> enterpriseMap = currentUser.getEnterpriseMap();
        if (enterpriseMap == null || enterpriseMap.size() == 0) {
            resultMap.put(JSON_RESULT, FAILED);
            resultMap.put(JSON_MSG, "当前用户没有企业ID");
            return resultMap;
        }
        String entId = "";
        for (Map.Entry<String, String> entry : enterpriseMap.entrySet()) {
            entId = entry.getKey();
        }
        noteVO.setEntId(entId);
        noteVO.setUpdateTime(new Date());
        noteVO.setOperTime(new Date());
        noteVO.setOperUserId(currentUser.getId());
        noteVO.setOperUserName(currentUser.getFullName());

        Map<String, Object> map = noteService.updateNote(noteVO);
        resultMap.put(JSON_RESULT, map.get("isOk"));
        resultMap.put(JSON_MSG, map.get("errorMessage"));
        resultMap.put("noteId", noteVO.getNoteId());
        return resultMap;
    }

    /**
     * 查询使签，不分页
     * 
     * @param OrderNotes
     */
    @ResponseBody
    @RequestMapping(value = "/getNoteList")
    public Map<String, Object> getNoteList(@RequestParam String busiKey) {
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        try {

            List<NoteVO> list = noteService.getNotesByBusiKey(busiKey);
            // 设置返回结果内容
            returnMap = getSuccessMap("获取内部便签列表成功");
            returnMap.put(RETURN_DATA, list);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 删除便签，只能删除自己的OrderNotes，不能删除其它人的
     * 
     * @param OrderNotes
     */
    public Map<String, Object> deleteNote(@RequestBody NoteVO noteVO) {
        return null;
    }

    /**
     * 查询便签，可以查看订单所有人写的便签
     * 
     * @param OrderNotes
     */
    @ResponseBody
    @RequestMapping(value = "/getNotesPaged")
    public Map<String, Object> getNotesPaged(@RequestBody NoteVO noteVO) {
        return null;
    }

    /**
     * 查询使签，不分页
     * 
     * @param OrderNotes
     */
    @ResponseBody
    @RequestMapping(value = "/getNotes")
    public Map<String, Object> getNotes(@RequestBody NoteVO noteVO) {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser == null) {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "当前用户失效");
                return returnMap;
            }
            Map<String, String> mapParm = new HashMap<String, String>();
            Map<String, String> enterpriseMap = currentUser.getEnterpriseMap();
            if (enterpriseMap == null || enterpriseMap.size() == 0) {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "当前用户没有企业ID");
                return returnMap;
            }
            String entId = "";
            String entName = "";
            for (Map.Entry<String, String> entry : enterpriseMap.entrySet()) {
                entId = entry.getKey();
                entName = entry.getValue();
            }

            noteVO.setEntId(entId);

            List<NoteVO> list = noteService.getNotes(noteVO);
            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, list);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * getSuccessMap:获取成功消息Map. <br/>
     *
     * @author zhanghao
     * @param message
     * @return
     * @since JDK 1.6
     */
    private Map<String, Object> getSuccessMap(String message) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, SUCCESS);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    };

    /**
     * getFailedMap:获取失败消息Map. <br/>
     *
     * @author zhanghao
     * @param message
     * @return
     * @since JDK 1.6
     */
    private Map<String, Object> getFailedMap(String message) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, FAILED);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    };

}